package com.lbn.jfqsc.app.login.register;

import android.text.TextUtils;

import com.lbn.baseframe.mvp.BasePresenter;
import com.lbn.baseframe.net.business.RxSubscribe;
import com.lbn.jfqsc.net.Host;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 李炳南
 * 2017/3/4.
 */

public class RegisterPresenter extends BasePresenter<IRegister> {

    private String phone, password, cPassword, UserName;

    private int type;

    public void register(String phone, String password, String cPassword, String UserName, int type) {
        this.phone = phone;
        this.password = password;
        this.cPassword = cPassword;
        this.UserName = UserName.trim();
        this.type = type;

        if (!isPhone(phone)) {
            getView().onError("请输入正确的手机号");
            return;
        }

        if(TextUtils.isEmpty(this.UserName)||TextUtils.isEmpty(password)||TextUtils.isEmpty(cPassword)){
            getView().onError("密码和名称不能为空");
            return;
        }

        if(!password.equals(cPassword)){
            getView().onError("两次输入密码不一致");
            return;
        }

        subscribeNetwork(Host.getApi().register(phone), new RxSubscribe() {
            @Override
            public void next(Object o) {
                    register();
            }

            @Override
            public void error(Throwable e) {
                getView().onError(e.getMessage());
            }
        });

    }


    public void register() {

        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("password",password);
        map.put("name",UserName);
        map.put("type",type+"");

        subscribeNetwork(Host.getApi().register(map), new RxSubscribe<Object>() {
            @Override
            public void next(Object o) {
                getView().onSucceed();
            }

            @Override
            public void error(Throwable e) {
                getView().onError(e.getMessage());
            }
        });

    }


    public boolean isPhone(String value) {

        String regExp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$";

        Pattern p = Pattern.compile(regExp);

        Matcher m = p.matcher(value);

        return m.find();//boolean
    }

}
